import json

import requests

from commonTool.logs.logs_wrapper import LogUtil

logs = LogUtil()


class http_tool:

    # 获取响应
    #
    # @Param    json_resp   响应报文
    # @Return
    @staticmethod
    def get_response(dataUrl, params=None):
        # 获取响应
        response = requests.get(dataUrl, params=params)
        responses = response.text.encode('utf-8').decode('utf-8')
        # 响应体转 JSON
        json_resp = json.loads(responses)
        return json_resp

    @staticmethod
    def post(http_url, header_params, body_params):
        try:
            header_params.update({'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
            logs.info(f"请求url：{http_url}")
            logs.info(f"请求头：{header_params}")
            logs.info(f"请求体：{body_params}")
            response = requests.post(http_url, headers=header_params, data=body_params.encode('utf-8'), timeout=60)
            logs.info(f"响应状态码：{response.status_code}")
            logs.info(f"响应内容：{response.text}")
            response.raise_for_status()  # 如果响应状态码为4xx或5xx，将引发HTTPError
            return response.text
        except requests.RequestException as e:
            print(f"HTTP post通信异常 {e}")
            return None
